<template>
  <div class="login">
    <div class="title">Login Form</div>
    <el-input v-model="loginForm.username" placeholder="请输入用户名">
       <i slot="prefix" class="el-input__icon el-icon-document"></i>
    </el-input>
    <el-input v-model="loginForm.password" placeholder="请输入密码" type="password">
       <i slot="prefix" class="el-input__icon el-icon-view"></i>
    </el-input>
    <el-row>
      <el-button @click="login()" type="primary">登陆</el-button>
      <el-button @click="get()" type="primary">GET</el-button>
      <el-button @click="clear()" type="primary">CLEAR</el-button>
    </el-row>
  </div>
</template>

<script>
// 刷新后动态路由失效
// 解决思路：登陆后保存 username 到 vuex 以及路由信息到 localStorage 刷新后 vuex 清空， router 在 beforeEach 中判断如果 vuex username 为空且 localStorage 存在 router 则重新添加路由信息

// 登陆逻辑
// 校验用户名密码=>通过后请求登录接口=>通过后拉取动态路由列表=>通过后存储动态路由至localStorage=>加载动态路由加载侧边导航

// 存储分析
// cookie
// vuex 首页各交互组件的数据
// sessionStorage
// localStorage 用户非敏感信息 动态路由 token
import { apiLogin } from '@/api/login'
import { apiGetMenuList } from '@/api/layout'
import { setStorage, getStorage, clearAllStorage } from '@/utils/localStorage.js'
import { addRoute } from '@/router/index.js'

export default {
  data () {
    return {
      loginForm: {
        username: 'admin',
        password: '123456'
      }
    }
  },
  mounted () {
    window.onbeforeunload = function () {
      console.log('refresh')
    }
  },
  methods: {
    get () {
      console.log(this.$store.state.app.user)
      console.log(getStorage('routesAsync'))
      console.log(getStorage('token'))
      console.log(getStorage('user'))
    },
    clear () {
      clearAllStorage()
    },
    login () {
      apiLogin(this.loginForm).then(res => {
        // 失败提示并清除密码
        if (!res.data.success) {
          this.$message.error('用户名或密码错误！')
          this.loginForm.password = null
          return false
        }
        let token = res.data.token
        let user = res.data.user

        // 拉取动态路由列表
        apiGetMenuList().then(res => {
          // 保存动态路、用户信息、token由到 storage
          setStorage('routesAsync', res.data)
          setStorage('token', token)
          setStorage('user', user)
          // 添加动态路由
          addRoute()
          // 路由跳转
          this.$router.push({ name: 'main' })
        })
        //
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: $c-bg-blue;

  @include flex-v-ac;
  justify-content: center;

  .title {
    font-size: 2rem;
    font-weight: bold;
    padding: 1rem;
  }

  .el-input {
    width: 40%;
    padding: 1rem 0;
  }
}
</style>
